package com.example.wifidirect

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.wifi.p2p.WifiP2pConfig
import android.net.wifi.p2p.WifiP2pDevice
import android.net.wifi.p2p.WifiP2pManager
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest
import android.os.IBinder
import android.util.Log

class DiscoverService : Service() {
    private val manager: WifiP2pManager by lazy(LazyThreadSafetyMode.NONE) {
        getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
    }
    private lateinit var channel: WifiP2pManager.Channel

    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // Registers the application with the Wi-Fi framework.
        channel = manager.initialize(this, mainLooper) {
            Log.d("onChannelDisconnected", "The channel to the framework has been disconnected.")
        }

        addDiscoverServiceRequest()

        return START_STICKY
    }

    private fun addDiscoverServiceRequest() {
        /* Callback includes:
         * fullDomain: full domain name: e.g. "printer._ipp._tcp.local."
         * record: TXT record dta as a map of key/value pairs.
         * device: The device running the advertised service.
         */
        val txtListener = WifiP2pManager.DnsSdTxtRecordListener { fullDomainName, txtRecordMap, srcDevice ->
            Log.d("DnsSdTxtRecord", "DnsSdTxtRecord available - $fullDomainName, $txtRecordMap, $srcDevice")
//            txtRecordMap["buddyname"]?.also {
//                buddies[srcDevice.deviceAddress] = it
//            }
        }

        val servListener =
            WifiP2pManager.DnsSdServiceResponseListener { instanceName, registrationType, srcDevice ->
                // Update the device name with the human-friendly version from
                // the DnsTxtRecord, assuming one arrived.
//                srcDevice.deviceName =
//                    buddies[srcDevice.deviceAddress] ?: srcDevice.deviceName

                Log.d("DnsSdService", "发现服务实例: $instanceName, 类型: $registrationType, 设备: ${srcDevice.deviceName}")
                if (instanceName == "ultrasound_ranging") {
                    connectToDevice(srcDevice)
                }

            }

        manager.setDnsSdResponseListeners(channel, servListener, txtListener)

        val serviceRequest = WifiP2pDnsSdServiceRequest.newInstance()
        manager.addServiceRequest(
            channel,
            serviceRequest,
            object : WifiP2pManager.ActionListener {
                override fun onSuccess() {
                    // Success!
                }

                override fun onFailure(code: Int) {
                    // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
                }
            }
        )
    }

    @SuppressLint("MissingPermission")
    private fun connectToDevice(device: WifiP2pDevice) {
        val config = WifiP2pConfig()
        config.deviceAddress = device.deviceAddress

        manager.connect(channel, config, object : WifiP2pManager.ActionListener {
            override fun onSuccess() {
                Log.d("connectToDevice", "success")
//                manager.requestConnectionInfo(channel) {
//                    Log.d("WiFiP2P", "is groupFormed: ${it.groupFormed}")
//                    //                    text.value = "groupFormed=${it.groupFormed}, isGroupOwner=${it.isGroupOwner}"
//                    if (it.groupFormed) {
//                        val isGroupOwner = it.isGroupOwner
//                        val addr = it.groupOwnerAddress
//                        Log.d("is Group Owner?", "$isGroupOwner")
//                        Log.d("address of GO?", "$addr")
//
//                        if(isGroupOwner) {
//
//                        } else {
//                            //                            if (!client.isClientSocketRunning()) {
//                            //                                it.groupOwnerAddress.hostAddress?.let { it1 -> client.startClient(it1) }
//                            //                            }
//                            //                            client.write("Ping")
//                        }
//                    }
//
//                }
            }

            override fun onFailure(reasonCode: Int) {
                Log.e("connectToDevice", "连接失败，错误码: $reasonCode")
            }
        })
    }
}